package store.lunangangster.nodeflow.parser.el.operator;

import static store.lunangangster.nodeflow.enums.FlowType.FLOW_IF;

import cn.hutool.core.collection.CollUtil;
import com.ql.util.express.Operator;
import store.lunangangster.nodeflow.builder.FlowBuilder;
import store.lunangangster.nodeflow.core.component.IfComponent;
import store.lunangangster.nodeflow.exception.RuleSourceParseException;
import store.lunangangster.nodeflow.parser.el.OperatorHelper;
import store.lunangangster.nodeflow.rt.element.Executable;
import store.lunangangster.nodeflow.rt.element.Node;
import store.lunangangster.nodeflow.rt.element.flow.IfFlow;
import store.lunangangster.nodeflow.util.Converter;

/**
 * 用于扩展IfFlow的ELSE操作符
 *
 * @author cwk
 * @version 1.0
 */
public class ElseIfOperator extends Operator {

  @Override
  public Object executeInner(Object[] list) {
    IfFlow ifFlow = Converter.convert(list[0], IfFlow.class);
    if (ifFlow.isElse()) {
      throw new RuleSourceParseException("Incompatible executable for ElseIfFlow: former IfFlow already has falseBranch, cannot use ELSEIF() or ELSE() again");
    }
    if (list.length != 3 || !(list[1] instanceof Node)) {
      throw new RuleSourceParseException("Incompatible executable for ElseIfFlow: should be like ELSEIF(ifNode, Flow)");
    }
    Node elseIfNode = Converter.convert(list[1], Node.class);
    if (!elseIfNode.isComponent(IfComponent.class)) {
      throw new RuleSourceParseException("Incompatible executable for ElseIfFlow: should have one and only IfNode");
    }
    IfFlow elseIfFlow = (IfFlow) FlowBuilder.buildELFLow(FLOW_IF, CollUtil.toList(elseIfNode));
    elseIfFlow.setTrueBranch(Converter.convert(list[2], Executable.class));
    // never be null
    OperatorHelper.findFalseBranchLeaf(ifFlow).setFalseBranch(elseIfFlow);
    return ifFlow;
  }

}
